import configparser
import os
import sys
import shutil
import codecs
import shlex
import subprocess as sp

from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager

#获取group_vars/all.yml所有参数到字典中
def read_config_para():
  myvars = {}
  with open("../group_vars/all.yml") as myfile:
    for line in myfile:
      name, var = line.partition(":")[::2]
      myvars[name.strip()] = var.strip()
  return myvars

def get_ansible_host_group_ip_list(groupname):
  inventory_file_name = '/etc/ansible/hosts'
  data_loader = DataLoader()
  inventory = InventoryManager(loader = data_loader, sources=[inventory_file_name])
  
  list = []
  for key in inventory.get_groups_dict()[groupname]:
    list.append(key)
  
  return list
  
#创建检查etcd集群运行状态脚本
def create_check_etcd_status_sh():
  myvars = read_config_para()

  etcdctl_cmd="ETCDCTL_API=3 etcdctl" \
                  + " --cacert=" + myvars["PKI_PATH"] + "/" + myvars["CA_SELF_SIGNED_CERTIFICATE"] \
                  + " --cert=" + myvars["PKI_PATH"] + "/" + myvars["ETCD_SELF_SIGNED_CERTIFICATE"] \
                  + " --key=" + myvars["PKI_PATH"] + "/" + myvars["ETCD_PRIVATE_KEY"] \
                  + " --endpoints=" + myvars["ETCD_ENDPOINTS"]
  etcdctl_para_status=" -w table endpoint status"
  etcdctl_para_health=" -w table endpoint health"

  #print(etcdctl_cmd+etcdctl_para_status)
  #print(etcdctl_cmd+etcdctl_para_health)

  fo = open("../inst-etcd/files/etcd_check.sh", "w")
  fo.write(etcdctl_cmd + etcdctl_para_status + "\n")
  fo.write(etcdctl_cmd + etcdctl_para_health + "\n")
  fo.close()

#从ansible hosts中获取etcd组中的ip及环境变量信息，并根据这些信息，配置etcd_url,etcd_endpoints，最终将参数写入../group_vars/all.yml
def modify_etcd_csr_json():
  inventory_file_name = '/etc/ansible/hosts'
  data_loader = DataLoader()
  inventory = InventoryManager(loader = data_loader, sources=[inventory_file_name])
  
  #print(inventory.get_groups_dict()['etcd'])
  etcd_url=""
  etcd_endpoints=""
  for key in inventory.get_groups_dict()['etcd']:
    cmd = "sed -i '/127.0.0.1/ i\        \"" + key + "\",' PKI/etcd-csr.json"
  #  print(cmd)
    os.system(cmd)
  #  print(key)
    host = inventory.get_host(key)
    vars=host.get_vars()
    etcdname=vars['etcdname']
    if etcd_url != "":
      etcd_url = etcd_url + "," 
      etcd_endpoints = etcd_endpoints + ","
    etcd_url = etcd_url + etcdname + "=" + "https:\/\/" + key  + ":2380"
    etcd_endpoints = etcd_endpoints + "https:\/\/" + key  + ":2379"
  
  etcd_url = "ETCD_URL: \"" + etcd_url + "\""
  etcd_endpoints = "ETCD_ENDPOINTS: \"" + etcd_endpoints + "\""
  #print(etcd_url)  
  #sed 's/^ETCD_URL.*$/abc/g' ../../../group_vars/all.yml
  cmd = "sed -i 's/^ETCD_URL.*$/" + etcd_url + "/g' ../group_vars/all.yml"
  #print(cmd)
  os.system(cmd)
  cmd = "sed -i 's/^ETCD_ENDPOINTS.*$/" + etcd_endpoints + "/g' ../group_vars/all.yml"
  os.system(cmd)
#  hostsList = inventory.groups['etcd'].get_hosts()
#  print(hostsList)

def modify_haproxy_conf():
  haproxy_config = "../inst-haproxy-keepalive/templates/haproxy.cfg.j2"
  myvars = read_config_para()
  
  # sed 找到关键字下面一行进行修改
  # sed '/listen admin_stats/{n;s/:.*$/:8888/;}' haproxy.cfg
  # 修改haproxy管理端口
  #cmd = "sed -i '/listen admin_stats/{n;s/:.*$/:" + myvars["HAPROXY_ADMIN_PORT"] +"/;}' " + haproxy_config
  #os.system(cmd)
  
  #cmd = "grep -n \"listen admin_stats\" " + haproxy_config + "| awk -F':' '{print $1}'"
  #val1 = sp.getoutput(cmd)
  #cmd = "grep -n \"listen kube-master\" " + haproxy_config + "| awk -F':' '{print $1}'"
  #val2 = sp.getoutput(cmd)
  # sed在指定行之间进行修改
  # sed '92,103s/stats auth .*$/stats auth admin:welcome1/' ../inst-haproxy-keepalive/files/haproxy.cfg
  # 修改haproxy管理用户名密码
  #cmd = "sed -i '" + val1 + "," + val2 + "s/stats auth .*$/stats auth " + myvars["HAPROXY_CONSOLE_USER"] + ":" \
  #       + myvars["HAPROXY_CONSOLE_PASSWD"] + "/' " + haproxy_config
  #os.system(cmd)
  
  # sed 匹配行后一行进行替换
  # 修改haproxy代理端口
  #cmd = "sed -i '/listen kube-master/{n;s/:.*$/:" + myvars["HAPROXY_KUB_API_PORT"] +"/;}' " + haproxy_config
  #os.system(cmd)
  
  # 添加需要负载均衡集群列表
  cmd = "grep -n \"listen kube-master\" " + haproxy_config + "| awk -F':' '{print $1}'"
  val = sp.getoutput(cmd)
  val = int(val) + 4
  for k8s_master_ip in get_ansible_host_group_ip_list("k8smaster"):
    str1 = "    server " + k8s_master_ip + " " + k8s_master_ip + ":" + myvars["KUB_API_SERVER_PORT"] + " check inter 2000 fall 2 rise 2 weight 1"
    # sed 指定行号后添加信息  
    cmd = "sed -i \'" + str(val) + " a\\" + str1 + "\' " + haproxy_config
    os.system(cmd)
    val = val + 1
  

def modify_kube_apiserver_csr_json():
  myvars = {}
  with open("../group_vars/all.yml") as myfile:
    for line in myfile:
      name, var = line.partition(":")[::2]
      myvars[name.strip()] = var.strip()
      
  inventory_file_name = '/etc/ansible/hosts'
  data_loader = DataLoader()
  inventory = InventoryManager(loader = data_loader,
                               sources=[inventory_file_name])
  for key in inventory.get_groups_dict()['k8smaster']:
    cmd = "sed -i '/127.0.0.1/ a\        \"" + key + "\",' PKI/kube-apiserver-csr.json"
    os.system(cmd)
  
  cmd = "sed -i '/127.0.0.1/ a\        \"" + myvars['VIP'] + "\",' PKI/kube-apiserver-csr.json"
  os.system(cmd)
  cmd = "sed -i '/127.0.0.1/ a\        \"" + myvars['CLUSTERIP'] + "\",' PKI/kube-apiserver-csr.json"
  os.system(cmd)

#print('hello, world')
#config = configparser.ConfigParser(allow_no_value=True)
#config.read("/etc/ansible/hosts")
#config.readfp(codecs.open("/etc/ansible/hosts", "r", "utf_8"))
#login = config['LOGIN']
#print(login["user"])
#for key, value in config.items('etcd'):
#   print(key)
#   cmd = "sed -i '/127.0.0.1/ i\        \"" + key + "\",' etcd-csr.json"
#   print(cmd)
#   os.system(cmd)

if os.path.exists("PKI/etcd-csr.json"):
  os.remove("PKI/etcd-csr.json")
if os.path.exists("PKI/kube-apiserver-csr.json"):
  os.remove("PKI/kube-apiserver-csr.json")
shutil.copyfile("etcd-csr.json.template", "PKI/etcd-csr.json")
shutil.copyfile("kube-apiserver-csr.json.template", "PKI/kube-apiserver-csr.json")
shutil.copyfile("haproxy.cfg.j2.template", "../inst-haproxy-keepalive/templates/haproxy.cfg.j2")

modify_etcd_csr_json()
create_check_etcd_status_sh()
modify_haproxy_conf()
modify_kube_apiserver_csr_json()


print("finish")

